package meb

import (
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gcache"
	"time"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// OauthPolling 查询授权结果  5秒轮询
func (ctl *Controller) OauthPolling(ctx *gin.Context) (err error) {
	args := hgin.ApiReq[OauthPollingArgs](ctx)

	body := &OauthPollingBody{Status: "0"}

	//前端本地开发环境设置登录状态
	if ctx.Request.Host == "localhost:80" {
		gcache.Set(ctl.cache, args.State, hgin.GenToken(hgin.Token{
			Uid:  "66d580d9bf128091a2bd94f6",
			Type: string(model.USER_TYPE_USR),
		}, time.Now().Add(365*24*time.Hour)), 10*time.Minute)
	}

	if token := gcache.Get[string](ctl.cache, args.State); token != "" {
		body.Status = "1"
		setJwtCookie(ctx, token)
	}

	hgin.ApiRes(ctx, body)
	return
}

type OauthPollingArgs struct {
	State string `json:"state"`
}

type OauthPollingBody struct {
	Status string `json:"status"` // 状态 1=正常 0=重试
}

func setJwtCookie(ctx *gin.Context, token string) {
	hgin.SetJwtCookie(ctx, token, 60*60*24*365) // 365天
}
